

jQuery(function ($) {
    var result;
    var addrs;
    var count;
    var user = JSON.parse(localStorage.getItem('user_info')) || {};
    var id = user.id;
    var userCity;
    var userDistrict;
    var userLocation;
    var userPhone;
    var userProvince;
    var userReceiver;
    var userStreet;
    var selected_goods = [];
    //解码
    var para = window.location.search;
    if (para) {
        var values = para.split("?");
        count = values[1].split("&")[1].split("=")[1];
        var goodId = values[1].split("&")[0].split("=")[1];
        var params = {
            "Goods": {
                "id": goodId
            },
            "GoodsImgs": {
                "main_flag": 1,
                "goods_id": goodId
            }
        };
        send_ajax('post', '/get', params, function callback(data) {
            if (data.code == 200) {
                result = data;
                if(result.Goods){
                    var curDate=new   Date();
                    //promotion_flag=1&(promotion_start<now&promotion_end>now || promotion_start==null)）
                    var promotionFlag = result.Goods.promotion_flag;
                    if(result.Goods.promotion_end){
                        var promotionFlagEnd = new Date(Date.parse((result.Goods.promotion_end).replace(/-/g,"/")));
                    }else{
                        var promotionFlagEnd =null;
                    }
                    var promotionFlagStart = new Date(Date.parse((result.Goods.promotion_start).replace(/-/g,"/")));
                    if(promotionFlag&&(promotionFlagStart<curDate&&promotionFlagEnd>curDate||promotionFlagEnd == null)){
                        result.Goods.goods_price = (result.Goods.promotion_price) ;
                        result.Goods.goodsPrice = (result.Goods.goods_price)*count
                    }else{
                        result.Goods.goods_price = (result.Goods.goods_price)
                        result.Goods.goodsPrice = (result.Goods.goods_price)*count 
                    }
                    renderAddressGrouping(result);
                } 
                
            }
        });
    }
    function renderAddressGrouping(result) {
        selected_goods = [];
        //选中的商品
        if (Object.prototype.toString.call(result) == '[object Array]') {
            selected_goods = result;
        } else {
            selected_goods.push(result);
        }
        var addressList = {
            "UserAddress[]": {
                "UserAddress": {
                    "user_id": id
                    //   "default_flag":1

                    //购物地址
                } } };

        if (id) {
            var url =window.location.search;
            send_ajax('post', '/get', addressList, function callback(data) {
                var isaddr_html = "";
                if (data.code == 200 && data["UserAddress[]"]) {
                    addrs = data["UserAddress[]"];
                    if(url.indexOf("addrId=") != -1){
                        var addresId = url.split('addrId=')[1];
                      var a_addr = addrs.filter(function (item) {
                            return item.id == addresId;
                        });
                        $('.send_address_top').attr('address-id',addresId);
                        joint_address(a_addr);
                    }else{
                        for (var h = 0; h < addrs.length; h++) {
                            if(addrs[h].default_flag==1){
                                joint_address(addrs[h]);
                                $('.send_address_top').attr('address-id',addrs[h].id)
                            }
                        }  
                    };
                    var price = 0;
                    for (var l = 0; l < selected_goods.length; l++) {
                        price += selected_goods[l].Goods.goodsPrice;
                        $('.send_address .list').append("<li class=\"item clearfix\" data-goods-id=" + selected_goods[l].Goods.id + ">\n                                <div class=\"clearfix\">\n                                    <div class=\"goods_pic\">\n                                        <a href=\"/goods-" + selected_goods[l].Goods.id + ".html\" target=\"_blank\"><img src=\"" + isImgHttp(selected_goods[l].GoodsImgs.thumb) + "\" alt=\"\"></a>\n                                    </div>\n                                    <div class=\"goods_content\">\n                                        <div>\n                                            <a href=\"/goods-" + selected_goods[l].Goods.id + ".html\" target=\"_blank\">\n                                            " + selected_goods[l].Goods.name + "\n                                            </a>\n                                        </div>\n                                        <div class=\"goods_price\">\n                                            <span>" + "￥" + keepTwoDecimalFull(selected_goods[l].Goods.goods_price)+'&nbsp'+'x'+'&nbsp'+count+selected_goods[l].Goods.unit_name+ "</span>\n                                        </div>\n                                    </div>\n                                </div>\n                               </li>");
                    };
                    $('.amount_payable_m').html('￥' + keepTwoDecimalFull(price));
                } else {
                    $('.send_address_top').append('<button class="add_address">您还没有注册地址，请点击注册!</button>');
                    for (var m = 0; m < selected_goods.length; m++) {
                        isaddr_html += '<li class="item clearfix">\n                                        <div class="clearfix">\n                                            <div class="goods_pic">\n                                                <a href="/goods-' + selected_goods[m].Goods.id + '.html" target="_blank">\n                                                <img src="' + isImgHttp(selected_goods[m].GoodsImgs.thumb) + '" alt="' + selected_goods[m].Goods.name + '"></a>\n                                            </div>\n                                            <div class="goods_content">\n                                                <div>\n                                                    <a>\n                                                    ' + selected_goods[m].Goods.name + '\n                                                    </a>\n                                                </div>\n                                                <div class="goods_price">\n                                                    <span>\uFFE5' + keepTwoDecimalFull(selected_goods[m].Goods.goods_price) + '</span>\n                                                </div>\n                                            </div>\n                                        </div>\n                                        <div class="remarks">\n                                            <strong>\u5907\u6CE8\u4FE1\u606F</strong>\n                                            <input type="text" placeholder="\u5B9A\u5236\u7C7B\u5546\u54C1\u8BF7\u5C06\u5546\u54C1\u4FE1\u606F\u505A\u8BE6\u7EC6\u8BF4\u660E"></input>\n                                        </div>\n                                    </li>';
                    };
                    $('.list').html(isaddr_html);
                }
            });
        } else {
            window.location.href = "/login/login.html";
        }
    }
    //拼接购物地址
    function joint_address(address) {
        var address = address[0]
        var area_ids = {
            "Area[]": {
                "count": 10,
                "Area": {
                    "use_flag": 1,
                    "id{}": [address.province, address.city, address.district, address.street]
                }
            }
        };
        send_ajax('post', '/get', area_ids, function callback(data) {
            if (data.code == 200&&data["Area[]"]) {
                //修改主数据
                var addr_info = data["Area[]"];
                address.province_obj = addr_info[0];
                address.city_obj = addr_info[1];
                address.district_obj = addr_info[2];
                address.street_obj = addr_info[3];
                // if($('.send_address_top').attr('address-id')==address.id){
                    userCity = address.city;
                    userDistrict = address.district;
                    userLocation = address.location;
                    userPhone = address.phone;
                    userProvince = address.province;
                    userReceiver = address.receiver;
                    userStreet = address.street;
                    $('.send_address_top').html('<p class="getAddrParam" data-address_id="'+address.id+'">' + address.receiver + "&nbsp" + address.phone + '</p>\n                        <p>' + (address.province_obj?address.province_obj.name:'') + "&nbsp" + (address.city_obj?address.city_obj.name:'') + "&nbsp" + (address.district_obj != undefined ? address.district_obj.name : '') + "&nbsp" + (address.street_obj != undefined ? address.street_obj.name : '') + "&nbsp" + address.location + '</p> ');
                // }
            }
        });
    };
    //渲染弹窗的地址
    function renderAddress(addr) {
        var addrHtml = "";
        for (var i = 0; i < addr.length; i++) {
            addrHtml += "<li class=\"address_item\" data-id=" + addr[i].id + '>\n                            <p>\n                                \u59D3\u540D\uFF1A' + addr[i].receiver + '\n                            </p>\n                             <p>\n                                \u7535\u8BDD: ' + addr[i].phone + '\n                            </p>\n                            <p>\n                               \u5730\u5740: ' +( addr[i].province_obj?addr[i].province_obj.name:'') + (addr[i].city_obj?addr[i].city_obj.name:'') + (addr[i].district_obj?addr[i].district_obj.name:'') + (addr[i].location?addr[i].location:'') + "\n                            </p>\n                            <p class=\"use_address\" data-address_id=\"" + addr[i].id + '">\n                                \u4F7F\u7528\u6B64\u5730\u5740\n                            </p>\n                        </li>';
        };

        $('.address_list').html(addrHtml);
        //使用此地址
        $('.use_address').click(function () {
            var addrId = $(this).attr('data-address_id');
            window.location.href = "/goods/other_order.html?goods_id="+goodId + "&count=" + count+"&addrId="+addrId;
        });
    }
      //使用其他地址切换
    if(id){
        $(document).on('click', '.other_address', function () {
            if ($('.change_address').hasClass('open')) {
                $('.change_address').removeClass('open');
            } else {
                $('.change_address').removeClass('open');
                $('.change_address').addClass('open');
            }
            renderAddress(addrs);
       }); 
    }else{
        //修改地址
        $(document).on('click', '.modify_addres', function () {
            if (!shopAddress) {
                $("#dialog").dialog({
                    // width:690,
                    modal: true
                });
                return;
            }
            var html = "";
            var addrClick = shopAddress.UserAddress;
            province_id = addrClick.province;
            city_id = addrClick.city;
            area_id = addrClick.district;
            town_id = addrClick.street;
            var city = addrClick.city_obj.name; //市
            var district = addrClick.district_obj != undefined ? addrClick.district_obj.name : '';
            var province = addrClick.province_obj.name; //省
            if (addrClick.street_obj != undefined) {
                var street = addrClick.street_obj.name; //街道
                $('.town').show().removeAttr('disabled');;
            } else {
                var street = ""; //街道
                $('.town').hide();
            }
            var location = addrClick.location; //具体位置
            var receiver = addrClick.receiver; //接受者
            var phone = addrClick.phone; //电话
            $("#dialog").dialog({
                // width:690,
                modal: true
            });
            var option_province = document.querySelector('.province option');
            var option_city = document.querySelector('.city option');
            var option_area = document.querySelector('.area option');
            var option_town = document.querySelector('.town option');
            $('.city').show().removeAttr('disabled');;
            $('.area').show().removeAttr('disabled');;
            $(option_province).text(province);
            $(option_city).text(city);
            $(option_area).text(district);
            $(option_town).text(street);

            $(option_province).val(addrClick.province);
            $(option_city).val(addrClick.city);
            $(option_area).val(addrClick.district);
            $(option_town).val(addrClick.street);
            $('.receiver').val(receiver);
            $('.detailed_txt').val(location);
            $('.phone').val(phone);
        });
    }
    $(document).on('click', '.add_address', function () {
        $('.change_address').removeClass('open');
        $("#dialog").dialog({
            // width:690,
            modal: true
        });
    });
  
    $('.cancel_address').click(function () {
        $("#dialog").dialog('close');
    });
    // var reg = /^1[3456789]\d{9}$/; //手机号码;
    var reg = /[0-9]{6,20}/; //手机号码
    //保存收货地址
    var province_id = '';
    var city_id = '';
    var area_id = '';
    var town_id = '';
    $('.save_information').click(function () {
        var province = $('.province').val();
        var city = $('.city').val();
        var area = $('.area').val();
        var town = $('.town').val();
        var receiver = $('.receiver').val();
        var detailed_txt = $('.detailed_txt ').val();
        var phone = $.trim($(".phone").val());
        var mailbox = $.trim($(".mailbox").val());
        var fixedPhone = $.trim($(".fixedPhone").val());
        //非空验证
        if (receiver == "") {
            $('.receiver_msg').show();
            $('.receiver_msg').html('请您填写收货人姓名');
        } else {
            $('.receiver_msg').hide();
        }
        if (detailed_txt == "") {
            $('.detailed_msg').show();
            $('.detailed_msg').html('请您填写收货人详细地址');
        } else {
            $('.detailed_msg').hide();
        }

        //手机号码
        if (phone == "") {
            $('.phone_msg').show();
            $('.phone_msg').html('请您填写收货人手机号码');
        } else if (reg.test(phone)) {
            $('.phone_msg').hide();
        } else {
            $('.phone_msg').show();
            $('.phone_msg').html('手机号格式不对，请重新输入');
        }
        //保存收货地址
        var flag;
        if ($('.checkbox').is(':checked')) {
            flag = 1;
        } else {
            flag = 0;
        };

        if (province != '' && city != '' && area != '' && detailed_txt != '' && receiver != '' && phone != '') {
            $('.localInfo').hide();
            if (!isLinkage) {
                var params = {
                    "UserAddress": {
                        "city": city_id,
                        "default_flag": flag,
                        "district": area_id,
                        "location": detailed_txt,
                        "phone": phone,
                        "province": province_id,
                        "receiver": receiver,
                        "street": town_id,
                        "user_id": id
                    },
                    "TAG": "UserAddress"
                };
            } else {
                var params = {
                    "UserAddress": {
                        "city": cityId,
                        "default_flag": flag,
                        "district": areaId,
                        "location": detailed_txt,
                        "phone": phone,
                        "province": provinceId,
                        "receiver": receiver,
                        "street": townId,
                        "user_id": id
                    },
                    "TAG": "UserAddress"
                };
            }

            if (id) {
                send_ajax('post', '/post', params, function callback(result) {
                    if (result.code == 200) {
                        window.location.reload();
                        $("#dialog").dialog('close');
                    }
                });
            } else {
                localStorage.setItem("address", JSON.stringify(params));
                window.location.reload();
                $("#dialog").dialog('close');
            }
        } else {
            $('.localInfo').show();
            $('.localInfo').html('请您填写完整的地区信息');
        }
    });
    //提交订单
    $('.sum_order').click(function () {
        var note_msg = $('.remarks_information').val();
        var addrId = $('.getAddrParam').attr('data-address_id');
        var coupon = $('#coupon').find("option:checked").attr("data-id");
        if (coupon == undefined) {
            coupon = 0;
        };
        var myDate = new Date();
        var day = myDate.getDate();
        var params;
        if (selected_goods.length) {
            var tempDate = []; //调教订单商品数据
            var map = {};
            for (var i = 0; i < selected_goods.length; i++) {
                var ai = selected_goods[i];
                if (!map[ai.Goods.id]) {
                    tempDate.push({
                        "goodsId": ai.Goods.id,
                        "count":  count
                    });
                }
            };
        };
        params = {
            'user_id': id ? id : 0,
            'goodsList': id ? tempDate : noUserTempDate,
            "note": note_msg,
            "addressId": addrId ? addrId : 0
        };
        //提交订单
        send_ajax('post', '/api/order/goods_submit', params, function (data) {
            if (data.code == 200) {
                var result = data.data;
                window.location.href="/goods/order_payment.html?order_sn=" + result;
            } else {
                alert(data.msg);
            }
        });
    });
    //四舍五入
    function keepTwoDecimalFull(num) {
        var result = parseFloat(num);
        if (isNaN(result)) {
            alert('传递参数错误，请检查！');
            return false;
        }

        result = Math.round(num * 100) / 100;

        var s_x = result.toString();
        var pos_decimal = s_x.indexOf('.');
        if (pos_decimal < 0) {
            pos_decimal = s_x.length;
            s_x += '.';
        }
        while (s_x.length <= pos_decimal + 2) {
            s_x += '0';
        }
        return s_x;
    };
 
  
});